namespace Test.ConsoleProgram.Algorithm.Solution
{
    [TestDescription("算法: 0112. 路径总和")]
    public class No0112_HasPathSum : AbsBaseTestItem
    {
        /*
        给定一个二叉树和一个目标和，判断该树中是否存在根节点到叶子节点的路径，这条路径上所有节点值相加等于目标和。
        说明: 叶子节点是指没有子节点的节点。
        */

        public class TreeNode
        {
            public int val;
            public TreeNode left;
            public TreeNode right;
            public TreeNode(int x) { val = x; }
        }

        public override void OnTest()
        {
            Assert.TestExe(HasPathSum,
                new TreeNode(5)
                {
                    left = new TreeNode(4)
                    {
                        left = new TreeNode(11)
                        {
                            left = new TreeNode(7),
                            right = new TreeNode(2),
                        },
                    },
                    right = new TreeNode(8)
                    {
                        left = new TreeNode(13),
                        right = new TreeNode(4)
                        {
                            right = new TreeNode(1),
                        },
                    },
                },
                22,
                true);
        }

        public bool HasPathSum(TreeNode root, int sum)
        {
            if (root == null)
            {
                return false;
            }
            if (root.left == null && root.right == null)
            {
                return root.val == sum;
            }
            return HasPathSum(root.left, sum - root.val) || HasPathSum(root.right, sum - root.val);
        }
    }
}
